<template>
  <!-- 输入组件 -->
  <view class="input-box">
    <uni-search-bar @input="input" cancelButton="none" radius="100"></uni-search-bar>
  </view>

  <!-- 搜索结果列表区域 -->
  <view class="sugg-list" v-if="searchResult.length!==0">
    <view class="sugg-item" v-for="li in searchResult" :key="li.goods_id" @click="goDetails(li)">
      <view class="g-name">{{li.goods_name}}</view>
      <uni-icons type="arrow-right" size="16"></uni-icons>
    </view>
  </view>

  <!-- 历史记录区域 -->
  <view class="his-box" v-else>
    <!-- 标题区域 -->
    <view class="his-title">
      <text>历史记录：</text>
      <uni-icons type="trash" size="17" @click="clearHis"></uni-icons>
    </view>

    <!-- 历史列表区域 -->
    <view class="his-list">
      <uni-tag class="tag" :text="hl" v-for="(hl,index) in histories" :key="index" @click="goGoodsDetails(hl)"> </uni-tag>
    </view>
  </view>

</template>

<script>
  import {
    escook
  } from '../../utils/escook';
  import {
    showMsg
  } from '../../utils/interact';
  export default {
    data() {
      return {
        timer: 0,
        kw: '',
        searchResult: [],
        historyList: []
      };
    },
    computed: {
      histories() {
        return [...this.historyList] = this.historyList.reverse();
      }
    },
    onLoad(){
      //页面初始化时获取历史记录
     this.historyList= JSON.parse(uni.getStorageSync('kw')) || "[]";
    },
    methods: {
      //搜索框的输入事件回调
      input(value) {
        clearTimeout(this.timer);

        this.timer = setTimeout(() => {
          this.kw = value;
          this.getSearchResult();

          this.saveKw();
        }, 500);
      },
      
      clearHis(){
        this.historyList=[];
        uni.removeStorageSync('kw');
      },
      
      goGoodsDetails(key){
        uni.navigateTo({
          url:'/subpkg/goods_list/goods_list?query='+key
        })
      },

      goDetails(good) {
        uni.navigateTo({
          url: '/subpkg/goods_details/goods_details?goods_id=' + good.goods_id
        })
      },

      //网络请求
      async getSearchResult() {
        
        //为什么对kw进行判断，因为当用户输入某个关键字后（此时searchResult已经被赋值），随后删除，此时不应该展示搜索结果，所以要把searchResult赋值为空数组
        if (this.kw === '') {
          this.searchResult = [];
          return
        }

        const {
          data: res
        } = await escook.get('api/public/v1/goods/qsearch', {
          query: this.kw
        });
        if (res.meta.status !== 200) return showMsg();

        this.searchResult = res.message;
      },

      //其他函数
      saveKw() {
        const set = new Set(this.historyList);

        set.delete(this.kw);

        set.add(this.kw);
        this.historyList = Array.from(set);

        //将搜索记录存入本地
        uni.setStorageSync('kw',JSON.stringify(this.historyList));
      }
    }
  }
</script>

<style lang="scss">
  //输入组件的粘性定位
  .input-box {
    position: sticky;
    top: 0%;
    z-index: 99;
  }

  // 搜索结果列表区域样式
  .sugg-list {
    padding: 0 10px;

    .sugg-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 13px 0;
      border-bottom: 1px solid black;

      .g-name {
        //文本过长换行的处理，三个属性配合
        white-space: nowrap; //不换行
        overflow: hidden; //溢出处理
        text-overflow: ellipsis;
        font-size: 30rpx;

      }
    }
  }

  // 搜索历史记录区域样式
  .his-box {

    .his-title {
      display: flex;
      justify-content: space-between;
      height: 40px;
      align-items: center;
      font-size: 33rpx;
      padding: 0 7px;
      border-bottom: 1px solid #333;
    }

    .his-list {
      display: flex;
      flex-wrap: wrap;
      overflow: hidden;

      .tag {
        margin: 3px 3px;
      }
    }
  }
</style>